const userModel = require("../../model/home/userModel")
const axios = require('axios')
class user {
	static async doLogin(ctx) {
		const { code } = ctx.query
		console.log(code, 5)
		var config = {
			method: 'get',
			url: `https://api.weixin.qq.com/sns/jscode2session?appid=wx21104338388c2471&secret=d42226caeff9e4c4258d66cd9d85b733&js_code=${code}&grant_type=authorization_code`,
		};
		let res = null
		try {
			// console.log('11')
			let resoult = await axios(config)
			// console.log(resoult.data.openid, 12)
			let inUserFlag = await userModel.getOpenId(resoult.data.openid)
			// console.log(inUserFlag, 14)
			if (!inUserFlag) {
				await userModel.addUser({ openid: resoult.data.openid, nickname: `用户${new Date().getTime()}` })
			}
			if (resoult.data.openid) {
				let users = await userModel.getUser(resoult.data.openid)
				res = { code: 0, codeInfo: "成功", data: users }
			} else {
				res = { code: 2, codeInfo: "报错了为获取openid" }
			}

			// console.log(users, 19)


		} catch (error) {
			res = { code: 1, codeInfo: "报错了" }
		}

		ctx.body = res

	}

	static async editUser(ctx) {
		const { nickname, headerurl, uid } = ctx.request.body
		if (!uid) {
			ctx.body = { code: 1, codeInfo: "参数不足" }

		} else {
			if (nickname) {
				await userModel.editUser({ uid, nickname }, 'nickname')
			}
			if (headerurl) {
				await userModel.editUser({ uid, headerurl }, 'headerurl')
			}
			ctx.body = { code: 0, codeInfo: "修改成功" }
		}


	}

	// 关注 和取消关注
	static async doFollow(ctx) {
		const { uid, nickname, guid } = ctx.request.body
		if (!uid || !guid || !nickname) {
			ctx.body = { code: 1, codeInfo: "参数不足" }
		} else {
			await userModel.doFollow(uid, guid, nickname)
			ctx.body = { code: 0, codeInfo: "操作成功" }
		}
	}

	static async getFollow(ctx) {
		let { uid, type, nowpage, pagesize } = ctx.request.query
		if (!nowpage) {
			nowpage = 1
		}
		if (!pagesize) {
			pagesize = 10
		}
		if (!uid || !type) {
			ctx.body = { code: 1, codeInfo: "参数不足" }
		} else {
			let res = null
			if (type === 'follow') {
				res = await userModel.getFollowList(uid, nowpage, pagesize)
			} else if (type === 'fans') {
				res = await userModel.getFansList(uid, nowpage, pagesize)
			} else {
				ctx.body = { code: 2, codeInfo: "参数错误" }
			}

			ctx.body = { code: 0, codeInfo: "获取成功", data: res }
		}
	}

	static async checkFollow(ctx){
		const { uid, guid } = ctx.request.query
		if (!uid || !guid) {
			ctx.body = { code: 1, codeInfo: "参数不足" }
		} else {
			let res = await userModel.getFollow(uid, guid)
			if (res.length > 0) {
				ctx.body = { code: 0, codeInfo: "已关注", data: true }
			} else {
				ctx.body = { code: 0, codeInfo: "未关注", data: false }
			}
		}
	}

}
module.exports = user